package com.skd.mall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.skd.common.dto.MemberPrice;
import com.skd.common.dto.SkuHasgStockDto;
import com.skd.common.dto.SkuReductionDTO;
import com.skd.common.dto.SpuboundsDTO;
import com.skd.common.dto.es.SkuESModel;
import com.skd.common.utils.R;
import com.skd.mall.product.dao.SpuInfoDescDao;
import com.skd.mall.product.entity.*;
import com.skd.mall.product.fegin.CouponFeginService;
import com.skd.mall.product.fegin.SearchFeginService;
import com.skd.mall.product.fegin.WareSkuFeginService;
import com.skd.mall.product.service.*;
import com.skd.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skd.common.utils.PageUtils;
import com.skd.common.utils.Query;

import com.skd.mall.product.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeginService couponFeginService;



    @Override
    public void saveSpuInfo(SpuInfoVo spuInfoVo) {
        //1保存SPU基本信息
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo,spuInfo);
        spuInfo.setUpdateTime(new Date());
        spuInfo.setCreateTime(new Date());
        this.save(spuInfo);
        //2保存SPU详细信息
        List<String> decripts = spuInfoVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfo.getId());
        descEntity.setDecript(String.join(",",decripts));
        spuInfoDescDao.insert(descEntity);
        //3保存图集信息
        List<String> images = spuInfoVo.getImages();
        List<SpuImagesEntity> imagesEntities = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoVo.getId());
            spuImagesEntity.setImgUrl(image);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(imagesEntities);
        //4保存规格参数
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfo.getId());
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setAttrValue(attr.getAttrValues());
            AttrEntity attrEntity = attrService.getOne(new QueryWrapper<AttrEntity>().eq("attr_id", attr.getAttrId()));
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setQuickShow(attr.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);
        //5保存当前SPU对应的SKU信息
        List<Skus> skus = spuInfoVo.getSkus();
        if(skus != null && skus.size()!=0){
            //保存sku基本信息
            skus.forEach((item) ->{
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoVo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images1 = item.getImages();
                String defultImage = "";
                for (Images images2:images1){
                    if(images2.getDefaultImg() == 1){
                        //表示默认的图片
                        defultImage = images2.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defultImage);
                skuInfoService.save(skuInfoEntity);
                //保存sku的图片信息
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map((img) -> {
                    SkuImagesEntity entity = new SkuImagesEntity();
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    entity.setImgUrl(img.getImgUrl());
                    entity.setDefaultImg(img.getDefaultImg());
                    return entity;
                }).filter(img->{
                    return img.getDefaultImg() == 1;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                //保存满减信息，折扣，会员价
                SkuReductionDTO dto =new SkuReductionDTO();
                BeanUtils.copyProperties(item,dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                if(item.getMemberPrice() !=null && item.getMemberPrice().size() >0){
                    List<MemberPrice> list = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice mDto = new MemberPrice();
                        mDto.setId(memberPrice.getId());
                        mDto.setPrice(memberPrice.getPrice());
                        mDto.setName(memberPrice.getName());
                        return mDto;
                    }).collect(Collectors.toList());
                    dto.setMemberPrice(list);
                }
                couponFeginService.saveFullReductionInfo(dto);
                //保存sku的销售信息
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map((sale) -> {
                    SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, entity);
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    return entity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            });
        }
        Bounds bounds = spuInfoVo.getBounds();
        SpuboundsDTO spuboundsDTO = new SpuboundsDTO();
        BeanUtils.copyProperties(bounds,spuboundsDTO);
        couponFeginService.saveSpuBounds(spuboundsDTO);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 设置对应的检索条件
        // 1. 关键字查询
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            // 需要添加关键字查询
            wrapper.and((w)->{
                w.eq("id",key)
                        .or().like("spu_name",key)
                        .or().like("spu_description",key);
            });
        }
        // status
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        // catalogId
        String catalogId = (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)){
            wrapper.eq("catalog_id",catalogId);
        }
        // brandId
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareSkuFeginService wareSkuFeginService;
    @Autowired
    private SearchFeginService searchFeginService;

    /**
     * 根据SPUID查询
     * */
    @Override
    public void up(Long spuId) {
        // 1.根据spuId查询相关的信息 封装到SkuESModel对象中
        List<SkuESModel> skuES = new ArrayList<>();
        // 根据spuID找到对应的SKU信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        // 对应的规格参数  根据spuId来查询规格参数信息
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(
                new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueEntities.stream().map(item -> {
            Long attrId = item.getAttrId();
            return attrId;
        }).collect(Collectors.toList());
        //查询到可以检索的属性
        List<AttrEntity> attrEntities = attrService.list(
                new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1));
        List<SkuESModel.Attrs> attrsList = attrEntities.stream().map(item -> {
            SkuESModel.Attrs attrs = new SkuESModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            List<ProductAttrValueEntity> collect = productAttrValueEntities.stream().filter(i -> {
                return i.getAttrId().equals(item.getAttrId());
            }).collect(Collectors.toList());
            collect.forEach(it->{
                attrs.setAttrValue(it.getAttrValue());
            });
            return attrs;
        }).collect(Collectors.toList());
        // 需要根据所有的skuId获取对应的库存信息---》远程调用
          //获取skuId集合
        List<Long> skuIds = skus.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());
        List<SkuHasgStockDto> skusHasStock = wareSkuFeginService.getSkusHasStock(skuIds);
          //变为map集合
        Map<Long, Boolean> skusHasStockMap = new HashMap<>();
        skusHasStock.forEach(item ->{
            skusHasStockMap.put(item.getSkuId(),item.getHasStock());
        });

        // 2.远程调用mall-search的服务，将SukESModel中的数据存储到ES中
        // 先实现属性的复制
        List<SkuESModel> skuESModels = skus.stream().map(item -> {
            SkuESModel model = new SkuESModel();
            BeanUtils.copyProperties(item, model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(
                    skuImagesService.getOne(
                    new QueryWrapper<SkuImagesEntity>().eq("sku_id",item.getSkuId())).getImgUrl());
            // hasStock 是否有库存 --》 库存系统查询  一次远程调用获取所有的skuId对应的库存信息
            if(skusHasStockMap == null){
                model.setHasStock(true);
            }else {
                model.setHasStock(skusHasStockMap.get(model.getSkuId()));
            }
            //热度分给零
            model.setHotScore(0L);
            // 品牌和类型的名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            model.setCatalogName(category.getName());
            //对应的规格参数
            model.setAttrs(attrsList);
            return model;
        }).collect(Collectors.toList());
        // 将SkuESModel中的数据存储到ES中
        R r = searchFeginService.productStatusUp(skuESModels);
        // 3.更新SPUID对应的状态
        // 根据对应的状态更新商品的状态
          // 远程调用成功  更新商品的状态为 上架
        if((Boolean) r.get("sof")){
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(1);
            this.updateById(spuInfoEntity);
        }else{
            // 远程调用失败
        }
    }

    @Override
    public List<OrderItemSpuInfoVo> getOrderItemSpuInfoSpuId(Long[] spuIds) {
        List<OrderItemSpuInfoVo> orderItemSpuInfoVos = new ArrayList<>();
        for (Long spuId : spuIds) {
            OrderItemSpuInfoVo vo = new OrderItemSpuInfoVo();
            SpuInfoEntity spuInfo = this.getById(spuId);
            vo.setId(spuInfo.getId());
            vo.setSpuName(spuInfo.getSpuName());
            vo.setSpuDescription(spuInfo.getSpuDescription());
            vo.setBrandId(spuInfo.getBrandId());
            //查询品牌名称
            BrandEntity brand = brandService.getById(spuInfo.getBrandId());
            vo.setBrandName(brand.getName());

            vo.setCatalogId(spuInfo.getCatalogId());
            //获取分类名称
            CategoryEntity category = categoryService.getById(spuInfo.getCatalogId());
            vo.setCatalogName(category.getName());

            //获取照片
            SpuInfoDescEntity descEntity = spuInfoDescDao.selectById(spuId);
            vo.setImg(descEntity.getDecript());

            orderItemSpuInfoVos.add(vo);
        }
        return orderItemSpuInfoVos;
    }

}